package wsp.dailymarket.deals;

import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.FacesRenderer;
import javax.faces.render.Renderer;

/**
 * Renders the title of a deals page
 * @author Matt
 */
@FacesRenderer(componentFamily = "javax.faces.Command", rendererType = "wsp.dailymarket.deals.DealTitle")
public class DealTitleRenderer extends Renderer {

	@Override
	public void encodeBegin(FacesContext context, UIComponent component)
			throws IOException {

		ResponseWriter writer = context.getResponseWriter();

		DealViewBean dealViewBean = (DealViewBean) context.getExternalContext().getRequestMap().get("dealView");

		boolean container_started = false;

		if (dealViewBean.getCatViewBean().getViewCategoryID() > 0) {
			this.startContainer(writer, component);
			container_started = true;
			writer.writeText(" > " + dealViewBean.getCatViewBean().getViewCategory().getName(), null);
			this.writeCloseLink(context, component, writer, dealViewBean, "cat");
		}
		if (!"".equals(dealViewBean.getFilterCompany())) {
			if (!container_started) {
				this.startContainer(writer, component);
				container_started = true;
			}
			writer.writeText(" > Company: " + dealViewBean.getFilterCompany(), null);
			this.writeCloseLink(context, component, writer, dealViewBean, "partner");
		}
		if (dealViewBean.getSearchQuery().length() > 0) {
			if (!container_started) {
				this.startContainer(writer, component);
				container_started = true;
			}
			writer.writeText(" > Search: \"" + dealViewBean.getSearchQuery() + "\"", null);
			this.writeCloseLink(context, component, writer, dealViewBean, "q");
		}
		if (container_started) {
			writer.endElement("div");
		}
	}

	private void startContainer(ResponseWriter writer, UIComponent component) throws IOException {
		writer.startElement("div", component);
		writer.writeAttribute("class", "deals-title", null);
	}

	private void writeCloseLink(FacesContext ctxt, UIComponent component, ResponseWriter writer, DealViewBean dealViewBean, String attribute) throws IOException {
		writer.startElement("a", component);
		writer.writeAttribute("href", dealViewBean.buildRestLink(attribute), null);
		writer.startElement("img", component);
		writer.writeAttribute("src", ctxt.getApplication().getViewHandler().getResourceURL(ctxt, "resources/images/icons/16/cross.png"), null);
		writer.writeAttribute("alt", "x", null);
		writer.writeAttribute("style", "vertical-align: middle; margin-left: 5px;", null);
		writer.endElement("img");
		writer.endElement("a");
	}
}
